export async function _renderPaintInOrder(ctx: any, fill: any, stroke: any) {
  // await drawFillStyle(ctx, fillStyle)
  if (fill) {
    ctx.fillStyle = typeof fill == 'string' ? fill : await fill._render()
    ctx.fill()
  }
  if (stroke) {
    ctx.strokeStyle =
      typeof stroke == 'string' ? stroke : await stroke._render()
    ctx.stroke()
  }
}
// 颜色生成器
export class Colour {
  type = 'color'
  color = ''
  radialGradient: any = {}
  linearGradient: any = {}
  gradualColor = []
  image = ''
  repeat = ''
  constructor(data: any) {
    for (let key in data) {
      ;(this as any)[key] = (data as any)[key]
    }
  }
  async _render(ctx: any) {
    let style: any
    if (this.type == 'color') {
      style = this.color
    }
    if (this.type == 'radialGradient') {
      // 环形渐变
      style = ctx.createRadialGradient(
        this.radialGradient.x0,
        this.radialGradient.y0,
        this.radialGradient.r0,
        this.radialGradient.x1,
        this.radialGradient.y1,
        this.radialGradient.r1
      )
    }

    if (this.type == 'linearGradient') {
      // 线形渐变
      style = ctx.createLinearGradient(
        this.linearGradient.x0,
        this.linearGradient.y0,
        this.linearGradient.x1,
        this.linearGradient.y1
      )
    }
    if (['linearGradient', 'radialGradient'].includes(this.type)) {
      this.gradualColor.forEach((item: any) => {
        style.addColorStop(item.step * 0.01, item.color)
      })
    }

    if (this.type == 'image') {
      let img = await getImage(this.image)
      style = ctx.createPattern(img, this.repeat)
    }
    return style
  }
}

// 设置实例对象阴影的相关配置
export const drawShadow = (ctx: any, shadow: any) => {
  ctx.shadowOffsetX = shadow.shadowOffsetX
  ctx.shadowOffsetY = shadow.shadowOffsetY
  ctx.shadowBlur = shadow.shadowBlur
  ctx.shadowColor = shadow.shadowColor
}

// 获取图片完成加载后的实例对象
export const getImage = (imgSrc: string) => {
  return new Promise((resolve, reject) => {
    let img = new Image()
    img.src = imgSrc
    img.crossOrigin = 'anonymous'
    img.onload = function () {
      resolve(img)
    }
  })
}
